package com.stu.concurrent;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.Condition;
import java.util.*;

/**
 * Java多线程和并发编程演示
 * 
 * 本类演示了Java并发编程的核心概念，包括：
 * 1. 线程的创建和生命周期
 * 2. 线程同步机制（synchronized、Lock、volatile）
 * 3. 线程间通信（wait/notify、Condition）
 * 4. 线程池的使用
 * 5. 并发工具类（CountDownLatch、CyclicBarrier、Semaphore）
 * 6. 原子类的使用
 * 7. ThreadLocal的使用
 * 8. 并发集合的使用
 * 
 * @author 学习者
 * @version 1.0
 * @since JDK 1.8
 */
public class ThreadAndConcurrencyDemo {
    
    // 共享资源，用于演示同步
    private static int sharedCounter = 0;
    private static final Object lock = new Object();
    private static final ReentrantLock reentrantLock = new ReentrantLock();
    
    // volatile变量演示
    private static volatile boolean flag = false;
    
    // ThreadLocal演示
    private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();
    
    /**
     * 主方法：演示多线程和并发编程的各个方面
     */
    public static void main(String[] args) throws InterruptedException {
        System.out.println("=== Java多线程和并发编程演示 ===");
        
        // 1. 演示线程的创建方式
        demonstrateThreadCreation();
        
        // 2. 演示线程生命周期
        demonstrateThreadLifecycle();
        
        // 3. 演示线程同步
        demonstrateThreadSynchronization();
        
        // 4. 演示volatile关键字
        demonstrateVolatile();
        
        // 5. 演示线程间通信
        demonstrateThreadCommunication();
        
        // 6. 演示线程池
        demonstrateThreadPool();
        
        // 7. 演示并发工具类
        demonstrateConcurrencyUtilities();
        
        // 8. 演示原子类
        demonstrateAtomicClasses();
        
        // 9. 演示ThreadLocal
        demonstrateThreadLocal();
        
        // 10. 演示并发集合
        demonstrateConcurrentCollections();
    }
    
    /**
     * 演示线程的创建方式
     */
    private static void demonstrateThreadCreation() throws InterruptedException {
        System.out.println("\n=== 线程创建方式 ===");
        
        System.out.println("Java中创建线程的方式：");
        System.out.println("1. 继承Thread类");
        System.out.println("2. 实现Runnable接口");
        System.out.println("3. 实现Callable接口（配合FutureTask）");
        System.out.println("4. 使用线程池");
        System.out.println("5. 使用Lambda表达式");
        
        // 方式1：继承Thread类
        System.out.println("\n方式1：继承Thread类");
        MyThread thread1 = new MyThread("Thread-1");
        thread1.start();
        thread1.join(); // 等待线程结束
        
        // 方式2：实现Runnable接口
        System.out.println("\n方式2：实现Runnable接口");
        MyRunnable runnable = new MyRunnable("Runnable-1");
        Thread thread2 = new Thread(runnable);
        thread2.start();
        thread2.join();
        
        // 方式3：实现Callable接口
        System.out.println("\n方式3：实现Callable接口");
        MyCallable callable = new MyCallable("Callable-1");
        FutureTask<String> futureTask = new FutureTask<>(callable);
        Thread thread3 = new Thread(futureTask);
        thread3.start();
        try {
            String result = futureTask.get(); // 获取返回值
            System.out.println("Callable返回值：" + result);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        
        // 方式4：使用Lambda表达式
        System.out.println("\n方式4：使用Lambda表达式");
        Thread thread4 = new Thread(() -> {
            System.out.println("Lambda线程执行：" + Thread.currentThread().getName());
        }, "Lambda-Thread");
        thread4.start();
        thread4.join();
        
        System.out.println("\n推荐使用方式：");
        System.out.println("- 实现Runnable接口：避免单继承限制，更灵活");
        System.out.println("- 使用线程池：避免频繁创建销毁线程，提高性能");
        System.out.println("- Lambda表达式：代码简洁，适合简单任务");
    }
    
    /**
     * 演示线程生命周期
     */
    private static void demonstrateThreadLifecycle() throws InterruptedException {
        System.out.println("\n=== 线程生命周期 ===");
        
        System.out.println("线程状态（Thread.State）：");
        System.out.println("1. NEW：新建状态，线程创建但未启动");
        System.out.println("2. RUNNABLE：可运行状态，包括运行中和就绪");
        System.out.println("3. BLOCKED：阻塞状态，等待获取锁");
        System.out.println("4. WAITING：等待状态，无限期等待其他线程");
        System.out.println("5. TIMED_WAITING：超时等待状态，有时限的等待");
        System.out.println("6. TERMINATED：终止状态，线程执行完毕");
        
        // 演示线程状态变化
        System.out.println("\n演示线程状态变化：");
        
        Thread stateDemo = new Thread(() -> {
            try {
                System.out.println("线程开始执行");
                Thread.sleep(1000); // TIMED_WAITING
                System.out.println("线程执行完毕");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "StateDemo");
        
        System.out.println("创建后状态：" + stateDemo.getState()); // NEW
        
        stateDemo.start();
        System.out.println("启动后状态：" + stateDemo.getState()); // RUNNABLE
        
        Thread.sleep(100);
        System.out.println("睡眠中状态：" + stateDemo.getState()); // TIMED_WAITING
        
        stateDemo.join();
        System.out.println("结束后状态：" + stateDemo.getState()); // TERMINATED
        
        System.out.println("\n线程控制方法：");
        System.out.println("- start()：启动线程");
        System.out.println("- join()：等待线程结束");
        System.out.println("- sleep()：线程休眠");
        System.out.println("- yield()：让出CPU时间片");
        System.out.println("- interrupt()：中断线程");
        System.out.println("- isAlive()：检查线程是否存活");
    }
    
    /**
     * 演示线程同步
     */
    private static void demonstrateThreadSynchronization() throws InterruptedException {
        System.out.println("\n=== 线程同步 ===");
        
        System.out.println("线程同步的必要性：");
        System.out.println("- 多线程访问共享资源时可能出现数据不一致");
        System.out.println("- 需要通过同步机制保证数据的一致性和完整性");
        
        // 演示不同步的问题
        System.out.println("\n演示不同步的问题：");
        demonstrateUnsynchronizedAccess();
        
        // 演示synchronized同步
        System.out.println("\n演示synchronized同步：");
        demonstrateSynchronizedAccess();
        
        // 演示Lock同步
        System.out.println("\n演示Lock同步：");
        demonstrateLockAccess();
        
        // 演示读写锁
        System.out.println("\n演示读写锁：");
        demonstrateReadWriteLock();
    }
    
    /**
     * 演示不同步访问的问题
     */
    private static void demonstrateUnsynchronizedAccess() throws InterruptedException {
        sharedCounter = 0;
        
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    sharedCounter++; // 非原子操作，可能出现数据竞争
                }
            });
        }
        
        for (Thread thread : threads) {
            thread.start();
        }
        
        for (Thread thread : threads) {
            thread.join();
        }
        
        System.out.println("不同步访问结果：" + sharedCounter + "（期望值：10000）");
        System.out.println("说明：由于数据竞争，结果通常小于期望值");
    }
    
    /**
     * 演示synchronized同步访问
     */
    private static void demonstrateSynchronizedAccess() throws InterruptedException {
        sharedCounter = 0;
        
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    synchronized (lock) {
                        sharedCounter++; // 同步访问
                    }
                }
            });
        }
        
        for (Thread thread : threads) {
            thread.start();
        }
        
        for (Thread thread : threads) {
            thread.join();
        }
        
        System.out.println("synchronized同步结果：" + sharedCounter + "（期望值：10000）");
        System.out.println("说明：通过synchronized保证了数据一致性");
        
        System.out.println("\nsynchronized的特点：");
        System.out.println("- 互斥性：同一时间只有一个线程可以执行同步代码");
        System.out.println("- 可见性：释放锁时会将变量刷新到主内存");
        System.out.println("- 可重入性：同一线程可以多次获取同一把锁");
        System.out.println("- 自动释放：方法结束或异常时自动释放锁");
    }
    
    /**
     * 演示Lock同步访问
     */
    private static void demonstrateLockAccess() throws InterruptedException {
        sharedCounter = 0;
        
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    reentrantLock.lock();
                    try {
                        sharedCounter++; // Lock同步访问
                    } finally {
                        reentrantLock.unlock(); // 必须在finally中释放锁
                    }
                }
            });
        }
        
        for (Thread thread : threads) {
            thread.start();
        }
        
        for (Thread thread : threads) {
            thread.join();
        }
        
        System.out.println("Lock同步结果：" + sharedCounter + "（期望值：10000）");
        
        System.out.println("\nLock vs synchronized：");
        System.out.println("Lock优势：");
        System.out.println("- 可中断：tryLock()可以尝试获取锁");
        System.out.println("- 可超时：tryLock(time, unit)支持超时");
        System.out.println("- 公平锁：可以指定公平性");
        System.out.println("- 条件变量：支持多个Condition");
        System.out.println("- 读写分离：ReadWriteLock支持读写分离");
        
        System.out.println("\nsynchronized优势：");
        System.out.println("- 语法简单：自动获取和释放锁");
        System.out.println("- JVM优化：偏向锁、轻量级锁等优化");
        System.out.println("- 异常安全：异常时自动释放锁");
    }
    
    /**
     * 演示读写锁
     */
    private static void demonstrateReadWriteLock() throws InterruptedException {
        ReadWriteLockDemo demo = new ReadWriteLockDemo();
        
        // 创建多个读线程
        Thread[] readers = new Thread[3];
        for (int i = 0; i < 3; i++) {
            final int readerId = i + 1;
            readers[i] = new Thread(() -> {
                for (int j = 0; j < 3; j++) {
                    demo.read(readerId);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            });
        }
        
        // 创建一个写线程
        Thread writer = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                demo.write("数据" + (i + 1));
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        
        // 启动所有线程
        for (Thread reader : readers) {
            reader.start();
        }
        writer.start();
        
        // 等待所有线程完成
        for (Thread reader : readers) {
            reader.join();
        }
        writer.join();
        
        System.out.println("\n读写锁特点：");
        System.out.println("- 读读并发：多个线程可以同时读");
        System.out.println("- 读写互斥：读和写不能同时进行");
        System.out.println("- 写写互斥：写和写不能同时进行");
        System.out.println("- 适用场景：读多写少的场景");
    }
    
    /**
     * 演示volatile关键字
     */
    private static void demonstrateVolatile() throws InterruptedException {
        System.out.println("\n=== volatile关键字 ===");
        
        System.out.println("volatile的作用：");
        System.out.println("1. 保证可见性：修改对其他线程立即可见");
        System.out.println("2. 禁止指令重排序：保证有序性");
        System.out.println("3. 不保证原子性：复合操作仍需要同步");
        
        // 演示volatile的可见性
        System.out.println("\n演示volatile可见性：");
        
        Thread writerThread = new Thread(() -> {
            try {
                Thread.sleep(1000);
                flag = true; // 修改volatile变量
                System.out.println("写线程：设置flag为true");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        
        Thread readerThread = new Thread(() -> {
            System.out.println("读线程：开始等待flag变为true");
            while (!flag) {
                // 等待flag变为true
                // 如果flag不是volatile，这个循环可能永远不会结束
            }
            System.out.println("读线程：检测到flag为true，退出循环");
        });
        
        readerThread.start();
        writerThread.start();
        
        readerThread.join();
        writerThread.join();
        
        System.out.println("\nvolatile使用场景：");
        System.out.println("1. 状态标志：如停止标志、初始化标志");
        System.out.println("2. 双重检查锁定模式中的实例变量");
        System.out.println("3. 独立观察：读取其他线程写入的值");
        
        System.out.println("\nvolatile vs synchronized：");
        System.out.println("volatile：轻量级，只保证可见性和有序性");
        System.out.println("synchronized：重量级，保证原子性、可见性和有序性");
    }
    
    /**
     * 演示线程间通信
     */
    private static void demonstrateThreadCommunication() throws InterruptedException {
        System.out.println("\n=== 线程间通信 ===");
        
        System.out.println("线程间通信方式：");
        System.out.println("1. wait/notify/notifyAll");
        System.out.println("2. Condition的await/signal/signalAll");
        System.out.println("3. BlockingQueue");
        System.out.println("4. CountDownLatch、CyclicBarrier等工具类");
        
        // 演示wait/notify
        System.out.println("\n演示wait/notify：");
        demonstrateWaitNotify();
        
        // 演示Condition
        System.out.println("\n演示Condition：");
        demonstrateCondition();
    }
    
    /**
     * 演示wait/notify机制
     */
    private static void demonstrateWaitNotify() throws InterruptedException {
        final Object waitNotifyLock = new Object();
        final List<String> messages = new ArrayList<>();
        
        // 消费者线程
        Thread consumer = new Thread(() -> {
            synchronized (waitNotifyLock) {
                try {
                    System.out.println("消费者：等待消息...");
                    waitNotifyLock.wait(); // 等待通知
                    System.out.println("消费者：收到通知，处理消息：" + messages.get(0));
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        
        // 生产者线程
        Thread producer = new Thread(() -> {
            synchronized (waitNotifyLock) {
                try {
                    Thread.sleep(1000);
                    messages.add("Hello from producer");
                    System.out.println("生产者：发送消息并通知消费者");
                    waitNotifyLock.notify(); // 通知等待的线程
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        
        consumer.start();
        producer.start();
        
        consumer.join();
        producer.join();
        
        System.out.println("\nwait/notify注意事项：");
        System.out.println("- 必须在synchronized块中使用");
        System.out.println("- wait会释放锁，notify不会释放锁");
        System.out.println("- 使用while循环检查条件，避免虚假唤醒");
        System.out.println("- notify随机唤醒一个线程，notifyAll唤醒所有线程");
    }
    
    /**
     * 演示Condition机制
     */
    private static void demonstrateCondition() throws InterruptedException {
        ReentrantLock conditionLock = new ReentrantLock();
        Condition condition = conditionLock.newCondition();
        final List<String> messages = new ArrayList<>();
        
        // 消费者线程
        Thread consumer = new Thread(() -> {
            conditionLock.lock();
            try {
                System.out.println("消费者：等待条件满足...");
                condition.await(); // 等待条件
                System.out.println("消费者：条件满足，处理消息：" + messages.get(0));
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                conditionLock.unlock();
            }
        });
        
        // 生产者线程
        Thread producer = new Thread(() -> {
            conditionLock.lock();
            try {
                Thread.sleep(1000);
                messages.add("Hello from producer with Condition");
                System.out.println("生产者：设置条件并发送信号");
                condition.signal(); // 发送信号
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                conditionLock.unlock();
            }
        });
        
        consumer.start();
        producer.start();
        
        consumer.join();
        producer.join();
        
        System.out.println("\nCondition vs wait/notify：");
        System.out.println("Condition优势：");
        System.out.println("- 一个Lock可以有多个Condition");
        System.out.println("- 支持公平性设置");
        System.out.println("- 支持超时等待");
        System.out.println("- 支持中断等待");
    }
    
    /**
     * 演示线程池
     */
    private static void demonstrateThreadPool() throws InterruptedException {
        System.out.println("\n=== 线程池 ===");
        
        System.out.println("线程池的优势：");
        System.out.println("1. 降低资源消耗：重用线程，减少创建销毁开销");
        System.out.println("2. 提高响应速度：任务到达时，无需等待线程创建");
        System.out.println("3. 提高线程的可管理性：统一分配、调优和监控");
        
        System.out.println("\n常用线程池类型：");
        
        // 1. FixedThreadPool
        System.out.println("\n1. FixedThreadPool（固定大小线程池）：");
        ExecutorService fixedPool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 5; i++) {
            final int taskId = i + 1;
            fixedPool.submit(() -> {
                System.out.println("FixedThreadPool - 任务" + taskId + 
                                 " 执行，线程：" + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        fixedPool.shutdown();
        fixedPool.awaitTermination(10, TimeUnit.SECONDS);
        
        // 2. CachedThreadPool
        System.out.println("\n2. CachedThreadPool（缓存线程池）：");
        ExecutorService cachedPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 3; i++) {
            final int taskId = i + 1;
            cachedPool.submit(() -> {
                System.out.println("CachedThreadPool - 任务" + taskId + 
                                 " 执行，线程：" + Thread.currentThread().getName());
            });
        }
        cachedPool.shutdown();
        cachedPool.awaitTermination(5, TimeUnit.SECONDS);
        
        // 3. SingleThreadExecutor
        System.out.println("\n3. SingleThreadExecutor（单线程池）：");
        ExecutorService singlePool = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 3; i++) {
            final int taskId = i + 1;
            singlePool.submit(() -> {
                System.out.println("SingleThreadExecutor - 任务" + taskId + 
                                 " 执行，线程：" + Thread.currentThread().getName());
            });
        }
        singlePool.shutdown();
        singlePool.awaitTermination(5, TimeUnit.SECONDS);
        
        // 4. ScheduledThreadPool
        System.out.println("\n4. ScheduledThreadPool（定时线程池）：");
        ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(2);
        
        // 延迟执行
        scheduledPool.schedule(() -> {
            System.out.println("延迟任务执行，线程：" + Thread.currentThread().getName());
        }, 1, TimeUnit.SECONDS);
        
        // 周期执行
        ScheduledFuture<?> periodicTask = scheduledPool.scheduleAtFixedRate(() -> {
            System.out.println("周期任务执行，线程：" + Thread.currentThread().getName());
        }, 0, 2, TimeUnit.SECONDS);
        
        // 运行一段时间后取消周期任务
        Thread.sleep(5000);
        periodicTask.cancel(false);
        scheduledPool.shutdown();
        
        System.out.println("\n线程池参数说明：");
        System.out.println("- corePoolSize：核心线程数");
        System.out.println("- maximumPoolSize：最大线程数");
        System.out.println("- keepAliveTime：空闲线程存活时间");
        System.out.println("- workQueue：任务队列");
        System.out.println("- threadFactory：线程工厂");
        System.out.println("- rejectedExecutionHandler：拒绝策略");
    }
    
    /**
     * 演示并发工具类
     */
    private static void demonstrateConcurrencyUtilities() throws InterruptedException {
        System.out.println("\n=== 并发工具类 ===");
        
        // 1. CountDownLatch
        System.out.println("\n1. CountDownLatch（倒计时门闩）：");
        demonstrateCountDownLatch();
        
        // 2. CyclicBarrier
        System.out.println("\n2. CyclicBarrier（循环屏障）：");
        demonstrateCyclicBarrier();
        
        // 3. Semaphore
        System.out.println("\n3. Semaphore（信号量）：");
        demonstrateSemaphore();
    }
    
    /**
     * 演示CountDownLatch
     */
    private static void demonstrateCountDownLatch() throws InterruptedException {
        System.out.println("CountDownLatch用途：等待多个线程完成后再继续执行");
        
        CountDownLatch latch = new CountDownLatch(3);
        
        // 创建3个工作线程
        for (int i = 0; i < 3; i++) {
            final int workerId = i + 1;
            new Thread(() -> {
                try {
                    System.out.println("工作线程" + workerId + "开始工作");
                    Thread.sleep(1000 + workerId * 500); // 模拟不同的工作时间
                    System.out.println("工作线程" + workerId + "完成工作");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    latch.countDown(); // 计数器减1
                }
            }).start();
        }
        
        System.out.println("主线程等待所有工作线程完成...");
        latch.await(); // 等待计数器归零
        System.out.println("所有工作线程完成，主线程继续执行");
        
        System.out.println("CountDownLatch特点：");
        System.out.println("- 一次性使用，不能重置");
        System.out.println("- 适用于一个线程等待多个线程完成的场景");
    }
    
    /**
     * 演示CyclicBarrier
     */
    private static void demonstrateCyclicBarrier() throws InterruptedException {
        System.out.println("CyclicBarrier用途：多个线程相互等待，到达屏障点后一起继续");
        
        CyclicBarrier barrier = new CyclicBarrier(3, () -> {
            System.out.println("所有线程都到达屏障点，执行屏障动作");
        });
        
        // 创建3个线程
        Thread[] threads = new Thread[3];
        for (int i = 0; i < 3; i++) {
            final int threadId = i + 1;
            threads[i] = new Thread(() -> {
                try {
                    System.out.println("线程" + threadId + "开始工作");
                    Thread.sleep(1000 + threadId * 300); // 模拟不同的工作时间
                    System.out.println("线程" + threadId + "到达屏障点，等待其他线程");
                    
                    barrier.await(); // 等待其他线程到达屏障点
                    
                    System.out.println("线程" + threadId + "继续执行后续工作");
                } catch (InterruptedException | BrokenBarrierException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        
        for (Thread thread : threads) {
            thread.start();
        }
        
        for (Thread thread : threads) {
            thread.join();
        }
        
        System.out.println("CyclicBarrier特点：");
        System.out.println("- 可以重复使用");
        System.out.println("- 适用于多个线程相互等待的场景");
        System.out.println("- 支持屏障动作，所有线程到达后执行");
    }
    
    /**
     * 演示Semaphore
     */
    private static void demonstrateSemaphore() throws InterruptedException {
        System.out.println("Semaphore用途：控制同时访问资源的线程数量");
        
        Semaphore semaphore = new Semaphore(2); // 允许2个线程同时访问
        
        // 创建5个线程竞争资源
        Thread[] threads = new Thread[5];
        for (int i = 0; i < 5; i++) {
            final int threadId = i + 1;
            threads[i] = new Thread(() -> {
                try {
                    System.out.println("线程" + threadId + "请求访问资源");
                    semaphore.acquire(); // 获取许可
                    
                    System.out.println("线程" + threadId + "获得许可，开始使用资源");
                    Thread.sleep(2000); // 模拟使用资源
                    System.out.println("线程" + threadId + "使用完毕，释放资源");
                    
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    semaphore.release(); // 释放许可
                }
            });
        }
        
        for (Thread thread : threads) {
            thread.start();
        }
        
        for (Thread thread : threads) {
            thread.join();
        }
        
        System.out.println("Semaphore特点：");
        System.out.println("- 控制并发访问数量");
        System.out.println("- 支持公平性设置");
        System.out.println("- 适用于资源池、连接池等场景");
    }
    
    /**
     * 演示原子类
     */
    private static void demonstrateAtomicClasses() throws InterruptedException {
        System.out.println("\n=== 原子类 ===");
        
        System.out.println("原子类的优势：");
        System.out.println("1. 无锁编程：基于CAS（Compare-And-Swap）操作");
        System.out.println("2. 高性能：避免了锁的开销");
        System.out.println("3. 线程安全：保证操作的原子性");
        
        // 演示AtomicInteger
        System.out.println("\n演示AtomicInteger：");
        AtomicInteger atomicCounter = new AtomicInteger(0);
        
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    atomicCounter.incrementAndGet(); // 原子递增
                }
            });
        }
        
        for (Thread thread : threads) {
            thread.start();
        }
        
        for (Thread thread : threads) {
            thread.join();
        }
        
        System.out.println("AtomicInteger结果：" + atomicCounter.get() + "（期望值：10000）");
        
        System.out.println("\n常用原子类：");
        System.out.println("- AtomicInteger/AtomicLong：原子整数");
        System.out.println("- AtomicBoolean：原子布尔值");
        System.out.println("- AtomicReference：原子引用");
        System.out.println("- AtomicIntegerArray：原子整数数组");
        System.out.println("- AtomicStampedReference：带版本号的原子引用（解决ABA问题）");
        
        System.out.println("\nCAS操作原理：");
        System.out.println("1. 比较：检查内存值是否等于期望值");
        System.out.println("2. 交换：如果相等，则更新为新值");
        System.out.println("3. 原子性：整个操作是原子的");
        System.out.println("4. 无锁：不需要获取锁，性能更好");
        
        System.out.println("\nCAS的问题：");
        System.out.println("1. ABA问题：值被改变后又改回原值");
        System.out.println("2. 循环时间长：自旋可能消耗CPU");
        System.out.println("3. 只能保证一个共享变量的原子操作");
    }
    
    /**
     * 演示ThreadLocal
     */
    private static void demonstrateThreadLocal() throws InterruptedException {
        System.out.println("\n=== ThreadLocal ===");
        
        System.out.println("ThreadLocal的作用：");
        System.out.println("1. 线程隔离：每个线程都有自己的变量副本");
        System.out.println("2. 避免参数传递：在线程内部共享数据");
        System.out.println("3. 线程安全：不需要同步机制");
        
        // 演示ThreadLocal的使用
        System.out.println("\n演示ThreadLocal使用：");
        
        Thread[] threads = new Thread[3];
        for (int i = 0; i < 3; i++) {
            final int threadId = i + 1;
            threads[i] = new Thread(() -> {
                // 设置ThreadLocal值
                threadLocal.set("线程" + threadId + "的数据");
                
                System.out.println("线程" + threadId + "设置ThreadLocal值：" + threadLocal.get());
                
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                
                System.out.println("线程" + threadId + "再次读取ThreadLocal值：" + threadLocal.get());
                
                // 清理ThreadLocal值，避免内存泄漏
                threadLocal.remove();
            });
        }
        
        for (Thread thread : threads) {
            thread.start();
        }
        
        for (Thread thread : threads) {
            thread.join();
        }
        
        System.out.println("\nThreadLocal使用场景：");
        System.out.println("1. 数据库连接：每个线程使用独立的连接");
        System.out.println("2. 用户会话：Web应用中存储用户信息");
        System.out.println("3. 事务管理：Spring的事务管理");
        System.out.println("4. 日期格式化：SimpleDateFormat线程不安全");
        
        System.out.println("\nThreadLocal注意事项：");
        System.out.println("1. 内存泄漏：使用完毕后调用remove()方法");
        System.out.println("2. 线程池：线程复用时可能读取到旧值");
        System.out.println("3. 父子线程：子线程不会继承父线程的ThreadLocal值");
        System.out.println("4. InheritableThreadLocal：支持父子线程传递");
    }
    
    /**
     * 演示并发集合
     */
    private static void demonstrateConcurrentCollections() throws InterruptedException {
        System.out.println("\n=== 并发集合 ===");
        
        System.out.println("并发集合的优势：");
        System.out.println("1. 线程安全：内部实现了同步机制");
        System.out.println("2. 高性能：针对并发场景优化");
        System.out.println("3. 无阻塞：大多数操作不会阻塞");
        
        // 演示ConcurrentHashMap
        System.out.println("\n演示ConcurrentHashMap：");
        ConcurrentHashMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();
        
        Thread[] mapThreads = new Thread[5];
        for (int i = 0; i < 5; i++) {
            final int threadId = i + 1;
            mapThreads[i] = new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    String key = "key" + (j % 10);
                    concurrentMap.compute(key, (k, v) -> (v == null) ? 1 : v + 1);
                }
                System.out.println("线程" + threadId + "完成ConcurrentHashMap操作");
            });
        }
        
        for (Thread thread : mapThreads) {
            thread.start();
        }
        
        for (Thread thread : mapThreads) {
            thread.join();
        }
        
        System.out.println("ConcurrentHashMap结果大小：" + concurrentMap.size());
        System.out.println("部分结果：" + concurrentMap.entrySet().stream().limit(3).toArray());
        
        // 演示BlockingQueue
        System.out.println("\n演示BlockingQueue：");
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
        
        // 生产者
        Thread producer = new Thread(() -> {
            try {
                for (int i = 1; i <= 10; i++) {
                    String item = "item" + i;
                    queue.put(item); // 阻塞式添加
                    System.out.println("生产者：添加 " + item);
                    Thread.sleep(100);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        
        // 消费者
        Thread consumer = new Thread(() -> {
            try {
                for (int i = 1; i <= 10; i++) {
                    String item = queue.take(); // 阻塞式获取
                    System.out.println("消费者：获取 " + item);
                    Thread.sleep(200);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        
        producer.start();
        consumer.start();
        
        producer.join();
        consumer.join();
        
        System.out.println("\n常用并发集合：");
        System.out.println("1. ConcurrentHashMap：并发哈希表");
        System.out.println("2. CopyOnWriteArrayList：写时复制列表");
        System.out.println("3. CopyOnWriteArraySet：写时复制集合");
        System.out.println("4. BlockingQueue：阻塞队列");
        System.out.println("   - ArrayBlockingQueue：有界阻塞队列");
        System.out.println("   - LinkedBlockingQueue：链表阻塞队列");
        System.out.println("   - PriorityBlockingQueue：优先级阻塞队列");
        System.out.println("   - SynchronousQueue：同步队列");
        System.out.println("5. ConcurrentLinkedQueue：并发链表队列");
        
        System.out.println("\n选择建议：");
        System.out.println("- 读多写少：CopyOnWriteArrayList/Set");
        System.out.println("- 频繁读写：ConcurrentHashMap");
        System.out.println("- 生产者消费者：BlockingQueue");
        System.out.println("- 高并发队列：ConcurrentLinkedQueue");
    }
}

/**
 * 继承Thread类的方式创建线程
 */
class MyThread extends Thread {
    private String threadName;
    
    public MyThread(String name) {
        this.threadName = name;
    }
    
    @Override
    public void run() {
        System.out.println(threadName + " 执行，线程ID：" + Thread.currentThread().getId());
    }
}

/**
 * 实现Runnable接口的方式创建线程
 */
class MyRunnable implements Runnable {
    private String taskName;
    
    public MyRunnable(String name) {
        this.taskName = name;
    }
    
    @Override
    public void run() {
        System.out.println(taskName + " 执行，线程：" + Thread.currentThread().getName());
    }
}

/**
 * 实现Callable接口的方式创建线程
 */
class MyCallable implements Callable<String> {
    private String taskName;
    
    public MyCallable(String name) {
        this.taskName = name;
    }
    
    @Override
    public String call() throws Exception {
        System.out.println(taskName + " 执行，线程：" + Thread.currentThread().getName());
        Thread.sleep(1000); // 模拟耗时操作
        return taskName + " 执行完成";
    }
}

/**
 * 读写锁演示类
 */
class ReadWriteLockDemo {
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private String data = "初始数据";
    
    /**
     * 读操作
     */
    public void read(int readerId) {
        lock.readLock().lock();
        try {
            System.out.println("读者" + readerId + " 开始读取：" + data + 
                             " [线程：" + Thread.currentThread().getName() + "]");
            Thread.sleep(1000); // 模拟读取时间
            System.out.println("读者" + readerId + " 读取完成");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock.readLock().unlock();
        }
    }
    
    /**
     * 写操作
     */
    public void write(String newData) {
        lock.writeLock().lock();
        try {
            System.out.println("写者开始写入：" + newData + 
                             " [线程：" + Thread.currentThread().getName() + "]");
            Thread.sleep(1500); // 模拟写入时间
            this.data = newData;
            System.out.println("写者写入完成：" + newData);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock.writeLock().unlock();
        }
    }
}